package com.nota.flink.cdc.exception;


import com.nota.flink.cdc.pojo.Result;
import com.nota.flink.cdc.utils.DingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private DingUtils dingUtils;

    public static final String TITLE = "flink-cdc 系统异常";

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<?> exceptionHandler(Exception e, HttpServletResponse response, HttpServletRequest request) {
        log.error("GlobalExceptionHandler", e);
        dingUtils.sendToDing(TITLE, "[nota-fink-cdc] " + e.getMessage());
        return Result.fail("", "The system is busy. Please try again later.");
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Result<?> exceptionHandler(MethodArgumentTypeMismatchException e, HttpServletResponse response) {

        log.error("RequestParamterError method: {}  params:{} error:{} ", e.getParameter().getMethod().getName(), e.getName(), e.getLocalizedMessage(), e);

        return Result.fail("", "require " + e.getRequiredType() + " " + e.getName());
    }


    /**
     * 捕获BizException,返回前端错误信息
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(BizException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result<?> bizExceptionHandler(BizException e) {
        log.error("业务异常信息 ex={}", e.getMessage(), e);
        return Result.failMsg(e.getLocalizedMessage());
    }


}
